package aiP.A3.Client.Monitor;

import aiP.A3.Client.Dispatcher.Dispatcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * User: Andreas
 * Date: 21.05.14
 * Time: 14:19
 * To change this template use File | Settings | File Templates.
 */
public class MonitorThread extends Thread {

    private Monitor monitor;

    private static final int CHECK_TIME = 5000;         // in Millisekunden
    private boolean tod = false;

    public MonitorThread(Monitor self){
        monitor = self;
    }

    public void toeten() {
        this.tod = true;
    }


    /**
     *
     */
    @Override
    public void run() {

        try {
            ServerSocket serverSocket = new ServerSocket(Monitor.SERVER_PORT);
            serverSocket.setReuseAddress(true);
            while (!this.tod) {
                Socket socket = serverSocket.accept();
                new RequestHandlerThread(socket).start();
            }
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private class RequestHandlerThread extends Thread {
        private final Socket socket;

        public RequestHandlerThread(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            try {
                BufferedReader buff = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                String id = buff.readLine();
                if (monitor.getInstanzenMap().containsKey(id)) {
                    Instance instance = monitor.getInstanzenMap().get(id);
                    instance.updateZuletztOnline();
                    instance.setLebendig();
                } else {
                    Instance instance = new Instance(id);
                    System.out.println("SystemTray: " +  monitor);
                    System.out.println("Instanz erstelle: "+ instance.getId().toString());
                    monitor.addInstanz(instance);
                }
                this.socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
